// [219]存在重复元素 II
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
        let mut map = std::collections::HashMap::new();
        for (i, num) in nums.iter().enumerate() {
            if let Some(idx) = map.get_mut(num) {
                if i.abs_diff(*idx) <= k as _ {
                    return true
                }
                *idx = i;
            } else {
                map.insert(num, i);
            }
        }
        false
    }
}
//leetcode submit region end(Prohibit modification and deletion)

#[test]
fn main() {
    let nums = vec![1, 2, 3, 1];
    let k = 3;
    assert_eq!(Solution::contains_nearby_duplicate(nums, k), true);
    let nums = vec![1, 0, 1, 1];
    let k = 1;
    assert_eq!(Solution::contains_nearby_duplicate(nums, k), true);
    let nums = vec![1, 2, 3, 1, 2, 3];
    let k = 2;
    assert_eq!(Solution::contains_nearby_duplicate(nums, k), false);
}
